package com.zhihaihe.file.interceptor;

import com.zhihaihe.file.advice.CommonException;
import com.zhihaihe.file.pojo.UserBean;
import com.zhihaihe.file.service.IUserService;
import com.zhihaihe.file.util.ResultCodeEnum;
import com.zhihaihe.file.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token验证拦截
 * @author
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 取得token
        String token = request.getHeader("token");
        if("undefined".equals(token) || !StringUtils.hasText(token)){
            token=request.getParameter("token不存在");
        }
        if ("undefined".equals(token) || !StringUtils.hasText(token)) {
            throw new CommonException("token不存在", ResultCodeEnum.NOT_LOGIN_ERROR.getCode());
        }

        token = token.replace("Bearer ", "");
        UserBean userBean = userService.getUserBeanByToken(token);
        SessionUtil.setSession(userBean);
        if (userBean == null) {
            throw new CommonException("token不存在", ResultCodeEnum.NOT_LOGIN_ERROR.getCode());
        }

        return true;
    }


}
